package com.zzyl.serve.service.impl;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.core.exception.ClientRequestException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author zengxze
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
//        1.从物联网上查询所有列表
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode()!=200){
            throw new BaseException("物联网列表查询失败");
        }

//        2.将列表缓存到redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY,
                JSONUtil.toJsonStr(response.getProducts()));
    }

    @Override
    public List<ProductVo> allProduct() {
//        从redis中查询产品列表
        String product =(String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);

//        判断是否查询到数据
        if (product==null && "".equals(product)){
            throw new BaseException("redis查询失败");
        }

//        返回查询到的数据
        return JSONUtil.toList(product, ProductVo.class);
    }

    @Override
    public void register(DeviceDto dto) {
//        判断设备标识码是否已存在
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getNodeId, dto.getNodeId());
        if (count(wrapper) > 0) {
            throw new BaseException("此设备已存在,请重新录入");
        }

//        判断设备名称是否已存在
        LambdaQueryWrapper<Device> wrapper1 = Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName());
        if (count(wrapper1) > 0) {
            throw new BaseException("从设备名称已存在,请重新录入");
        }

//        判断同一位置是否已经有同一产品
        LambdaQueryWrapper<Device> wrapper2 = Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getBindingLocation,dto.getBindingLocation());
        if (count(wrapper2) > 0) {
            throw new BaseException("该老人位置已绑定该产品,请重新选择");
        }

        AddDeviceRequest request = new AddDeviceRequest();
//        准备密钥
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString(true);
        authInfo.withSecret(secret);

//        新增数据
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());
        body.setAuthInfo(authInfo);

//        上传到华为云IoTDA服务
        request.withBody(body);
//        request.setInstanceId("2a755144-c116-4fc6-b74a-0ce42b3bbf8c");
        AddDeviceResponse response = client.addDevice(request);

        String iotId = response.getDeviceId();
//        封装Device对象实体类
//        拷贝属性
        Device  deviceSQL = new Device();
        BeanUtils.copyProperties(dto, deviceSQL);
        deviceSQL.setIotId(iotId);
        deviceSQL.setSecret(secret);
//        保存到数据库表
        save(deviceSQL);
    }

    @Override
    public List<ServiceCapability> queryProductProductKey(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
//        调用华为提供的方法,查询物联网上的数据
        ShowProductResponse response = client.showProduct(request);
        return response.getServiceCapabilities();
    }
}
